package com.wenlong.service.impl;

import com.wenlong.dao.CommodityDao;
import com.wenlong.dao.OrderDao;
import com.wenlong.dao.OrderItemDao;
import com.wenlong.dao.impl.CommodityDaoImpl;
import com.wenlong.dao.impl.OrderDaoImpl;
import com.wenlong.dao.impl.OrderItemDaoImpl;
import com.wenlong.pojo.*;
import com.wenlong.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @author 苏文龙
 * @version 1.0
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId,new Date(), cart.getTotalPrice(),0,userId);
        orderDao.saveOrder(order);
        System.out.println(12/0);
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            //获取购物车信息转为对应订单
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
            orderItemDao.saveOrderItem(orderItem);
            // 更新数据库销量 与 价格
            CommodityDao commodityDao = new CommodityDaoImpl();
            Commodity commodity = commodityDao.queryCommodityById(cartItem.getId());
            commodity.setSales(commodity.getSales() + cartItem.getCount());
            commodity.setStock(commodity.getStock() - cartItem.getCount());
            commodityDao.updateCommodity(commodity);
        }
        cart.clear();
        return orderId;
    }
}
